define(function (require, exports, module) {
    var $ = require("jquery");
    require("pagination");
    var util = require("util");
    var ui = require("ui");
    var angular = require("angular");
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    var moment = require('moment');
    var dialog = require("dialogplus");

    var raiseFinanceActivitiesModule = angular.module('raiseFinanceActivitiesModule', []);

    function raiseFinanceActivitiesService($http, $q, $location, $timeout) {
        var service = {
            // 基础数据是否加载
            loaded: false,
            // 项目列表
            projectList: [],
            // 选择的项目 ID
            projectId: '',
            activities: [],//活动列表
            total: 0,
            filter: {pageSize: 10},
            // 项目列表发生了变化
            projectChanged: function () {
                if (!service.projectId) {
                    return;
                }
            },

            initData: function () {
                var p = service.filter;
                service.query(p.pageIndex || 1, p.pageSize || 10, p.status || '', p.keyword || '');
            },

            query: function (pageIndex, pageSize, status, keyword) {
                service.filter = {pageIndex: pageIndex, pageSize: pageSize, status: status, keyword: keyword};
                $http.get(api_prefix + '/rclc/teambuy/get-teambuy-list', {params: service.filter})
                    .then(function (res) {
                        var retCode = res.data.retCode;
                        if (retCode == 0) {
                            var data = res.data.data;
                            service.activities = data.items;
                            service.total = data.total;
                            service.filter.pageIndex = pageIndex;
                        } else {
                            ui.showErrTip(res.data.errMsg);
                            return false;
                        }
                    });
            },
            // 初始化查询表单数据
            initEditActivitiesDialog: function ($data, $dialog, $dialogScope, activity) {
                var sale_pointModel = {};
                if (activity && activity.sale_point) {
                    var sale_points = activity.sale_point.split('##');
                    $.each(sale_points, function (i, d) {
                        sale_pointModel['sale_point' + (i + 1)] = d;
                    });
                }
                angular.extend($data, {
                    activity: $.extend(true, {rc_amount: 10000, imgList: []}, activity, sale_pointModel)
                });

                var endDate = moment($data.activity.end_date, 'YYYY-MM-DD HH:mm:ss');
                if (endDate.isValid()) {
                    $data.activity.end_date = endDate.format('YYYY-MM-DD');
                    $data.activity.end_time = endDate.format('HH:mm');
                }

                $dialogScope.url = '';
                $dialogScope.preview = '';
                $dialogScope.uploadImages = function (status) {
                    switch (status.status) {
                        case 'success':
                            setTimeout(function () {
                                $dialogScope.$apply(function () {
                                    $data.activity.imgList.push({
                                        img_url: $dialogScope.url,
                                        url: $dialogScope.url,
                                        preview: $dialogScope.preview,
                                        __type: 'add'
                                    });
                                });

                            }, 100);

                            break;
                        case 'error':
                            if (status.msg.toString().match(/File\s+size\s+error/)) {
                                $dialogScope.uploader.state = '图片大小超出限制';
                            } else if (status.msg.toString().match(/File\s+extension\s+error/)) {
                                $dialogScope.uploader.state = '图片类型不符';
                            }
                            else {
                                $dialogScope.uploader.state = status.msg;
                            }

                            break;
                    }
                }

                $dialogScope.validTimeFormat = function (time) {
                    if (!$data.activity.end_time) {
                        return false;
                    }
                    var time = $data.activity.end_time.toString();
                    if (time.match(/^[01][0-9]:[0-5][0-9]$|^[2][0-3]:[0-5][0-9]$/)) {
                        return false;
                    }

                    return true;
                };

                $dialogScope.validImages = function () {
                    var imgs = $data.activity.imgList;

                    if (imgs && imgs.length) {
                        var r = $.grep(imgs, function (o, i) {
                            if (o['__type'] == 'delete') {
                                return false;
                            }

                            return true;
                        })

                        return !r.length;
                    }

                    return true;

                };

                this.initEditor('ue-raise-finance-content', $data.activity.confirm_content);

                $dialogScope.showAgreement = function () {
                    service.showAgreement();
                }

                $dialogScope.validContent = function(){
                    return !service.editor.getContentTxt();
                }
            },

            initEditor: function (container, value) {
                var toolbar = window.UEDITOR_CONFIG.toolbarStyles["text"];
                var editor = new UE.ui.Editor({toolbars: toolbar});
                service.editor = editor;
                editor.ready(function () {
                    if (value) {
                        editor.setContent(value);
                    }
                });
                editor.render(container);
            },
            save: function ($data, $dialog) {
                //校验
                if ($('.error:visible').length) {
                    return false;
                }
                if (!$('#chklaw:checked').length) {
                    util.alert('请阅读并同意明源(腾讯"理财通"购房优惠活动)合作协议');
                    return false;
                }
                var sale_point = '';
                for (var i = 1; i <= 6; i++) {
                    sale_point += (sale_point ? '##' : '') + ($data.activity['sale_point' + i] || '');
                }
                var data = {
                    teambuy: angular.extend({},
                        $data.activity,
                        {sale_point: sale_point},
                        {confirm_content: service.editor.getContent()}
                    )
                };
                data.teambuy.end_date = data.teambuy.end_date + ' ' + data.teambuy.end_time + ':00';

                if (data.teambuy.onshelf == 1) {
                    data.teambuy.publish_status = 1;
                }
                var url = api_prefix + "/rclc/teambuy/add-teambuy";
                if (data.teambuy.teambuy_id) {
                    url = api_prefix + "/rclc/teambuy/update-teambuy";
                }

                if (data.teambuy.imgList && data.teambuy.imgList.length) {
                    var validata = $.grep(data.teambuy.imgList, function (o, i) {
                        if (o.__type == 'delete' && !o.teambuy_img_id) {
                            return false;
                        }
                        return true;
                    });
                    data.teambuy.imgList = validata;
                }
                util.myAjax({
                    url: url,
                    type: "POST",
                    data: data,
                    context: this,
                    success: function (json) {
                        if (json.retCode == 0) {
                            ui.showSucTip();
                            $timeout(function () {
                                service.initData();
                                $dialog.close();
                            }, 0);
                        } else {
                            ui.showErrTip(json.errMsg);
                        }
                    }
                });

                return false;
            },
            setStatus: function (teambuy, status) {
                var data = {teambuyId: teambuy.teambuy_id};
                var url = api_prefix + "/rclc/teambuy/publish-teambuy";
                if (status == 0) {
                    url = api_prefix + "/rclc/teambuy/unshelve-teambuy";
                }
                util.myAjax({
                    url: url,
                    type: "POST",
                    data: data,
                    context: this,
                    success: function (json) {
                        if (json.retCode == 0) {
                            service.initData();
                            ui.showSucTip();
                        } else {
                            ui.showErrTip(json.errMsg);
                        }
                    }
                });
            },
            showAgreement: function () {
                $http.get('activities/team_agreement.html')
                    .then(function (result) {
                        var d = dialog({
                            title: '合作协议',
                            content: $('<div style="height:450px;overflow:auto;"></div>').html(result.data),
                            fixed: true,
                            width: 650,
                            height: 450,
                            cancelValue: "关闭",
                            cancel: function () {
                            }
                        });
                        d.showModal();
                    });

            }
        };

        return service;
    }

    raiseFinanceActivitiesModule.factory('raiseFinanceActivities', ['$http', '$q', '$location', '$timeout', raiseFinanceActivitiesService]);

    module.exports = raiseFinanceActivitiesModule;
})
;